<template>
  <div>
    <t-card class="list-card-container">
      <template #title style="padding-bottom: 0px;">
        <t-input v-model="article.title" borderless clearable style="width:680px" placeholder="请输入文章标题"></t-input>
      </template>
      <template #actions >
          <t-space>
             <t-button @click="openAI" variant="outline"><template #icon><chart-bubble-icon /></template>AI生成</t-button>
                   <t-button @click="newPosts" variant="outline"><template #icon><add-icon /></template>新文章</t-button>
               <t-button @click="settingPosts" variant="outline"><template #icon><setting-icon /></template>设置</t-button>
                 </t-space>
      </template>

      <Editor :text="article.md" @onChange="changeContent" @onSave="save" ref="editor1"></Editor>

    </t-card>

    <PostSetting :visible="drawerVisible" :data="article" :metaData="metaData" :tagOptions="tagOptions"
    @onChange="changePostSetting" @onClose="closePostSetting" @onDelete="deletePost"></PostSetting>

    <AiArticle :visible="visibleAI" @onClose="visibleAI=false" @onComplete="aiComplete"></AiArticle>
  </div>
</template>

<script setup type="ts">
  import {nextTick, onMounted, ref,watch,reactive} from 'vue'
  import { useRouter,useRoute  } from 'vue-router';
  import $eventBus from '@/utils/eventBus'
  import Editor from '../../components/editor/index.vue'
  import {  MessagePlugin } from 'tdesign-vue-next';
  import { AddIcon,SettingIcon,ChartBubbleIcon  } from 'tdesign-icons-vue-next';
  import PostSetting from './components/postSettings.vue'
  import AiArticle from '../../components/ai/AiArticle.vue'
 import { getDraftsList, savePosts,deletePosts,getPosts,saveMeta } from '@/api/posts';
 import { getTagsList } from '@/api/tags';


  const router=useRouter()
  const route=useRoute ()
  const postsId=ref('')
  const articleContent={
    id:'',
    title:'',
    md:''
  }
  const editor1=ref(null)
  const editorText=ref('')
  const article=ref({...articleContent})
  const visibleAI=ref(false)
  const changeContent=(editor)=> {
        //console.log('text',editor.text)
        article.value.md = editor.text
        //console.log('article=',JSON.stringify(this.article) )
      }
  const save=(editor)=>{
    if (article.value.title == '') {
    	MessagePlugin.error('标题不能为空')
    	return
    }
    article.value.type='post'
    savePosts(article.value)
    .then(ret=>{
    	//console.log(JSON.stringify(ret))
      article.value.id=ret.id;
    	MessagePlugin.success('保存成功')
      metaData.value.post_id=ret.id
      saveMetaData(metaData.value)
    }).catch(err=>{
    	MessagePlugin.error(err.data)
    })
  }

  const newPosts=()=>{
    article.value={...articleContent.value}
    editorText.value=''
    metaData.value={
      post_id:'',
      meta_title:'',
      meta_description:''
    }
    console.log('newPosts' ,editorText.value)
  }
  const getPostsInfo=()=>{
    article.value={...articleContent}
    postsId.value=route.params.id
    console.log('postsId.value',postsId.value)
    if(postsId.value&&postsId.value!='')
    {
      nextTick(()=>{
          getPosts(postsId.value)
          .then(ret=>{
            article.value=ret;
            console.log('getPosts',JSON.stringify(ret))
            let d=ret.metas[0]
            if(d)
            {
              metaData.value.post_id=postsId.value
              metaData.value.meta_title=d.meta_title
              metaData.value.meta_description=d.meta_description
            }
          })
          console.log(JSON.stringify(article.value))
        })
    }

  }
  const openAI=()=>{
    visibleAI.value=true
  }
  const aiComplete=(d)=>{
    article.value.title=d.title
    article.value.md=d.content
  }
//设置
const drawerVisible = ref(false);
// 详情
const detailInfo = reactive({
  id: '',
  canonical_url: '',
  codeinjection_foot: '',
  codeinjection_head: '',
  created_at: '',
  created_by: '',
  feature_image: '',
  html: '',
  locale: '',
  mobiledoc: '',
  plaintext: '',
  published_at: '',
  published_by: '',
  show_title_and_feature_image: '',
  slug: '',
  status: '',
  title: '',
  type: '',
  updated_at: '',
  updated_by: '',
  uuid: '',
  visibility: '',
  tags:'',
  metas:[]
});
const handleClickDetail = (obj) => {
  getPosts(obj.row.id)
  .then(ret=>{
    detailInfo.id = ret.id;
       detailInfo.canonical_url = ret.canonical_url;
       detailInfo.codeinjection_foot = ret.codeinjection_foot;
       detailInfo.codeinjection_head = ret.codeinjection_head;
       detailInfo.created_at = ret.created_at;
       detailInfo.created_by = ret.created_by;
       detailInfo.feature = ret.feature;
       detailInfo.feature_image = ret.feature_image;
       detailInfo.html = ret.html;
       detailInfo.locale = ret.locale;
       detailInfo.mobiledoc = ret.mobiledoc;
       detailInfo.plaintext = ret.plaintext;
       detailInfo.published_at = ret.published_at;
       detailInfo.published_by = ret.published_by;
       detailInfo.show_title_and_feature_image = ret.show_title_and_feature_image;
       detailInfo.slug = ret.slug;
       detailInfo.status = ret.status;
       detailInfo.title = ret.title;
       detailInfo.type = ret.type;
       detailInfo.updated_at = ret.updated_at;
       detailInfo.updated_by = ret.updated_by;
       detailInfo.uuid = ret.uuid;
       detailInfo.visibility = ret.visibility;
       detailInfo.tags = ret.tags??'';
       detailInfo.metas=ret.metas;
       drawerVisible.value = true;

  })
  .catch(e=>{
    if(e.message)
    {
      MessagePlugin.error(e.message)
    }else
    {
      MessagePlugin.error(e.msg)
    }

  })
};
const closePostSetting=()=>{
  console.log('close post settings')
  console.log('detailInfo', JSON.stringify(detailInfo))
  drawerVisible.value=false
  save()
}
const changePostSetting=(d)=>{
  console.log('detailInfo',JSON.stringify(detailInfo))
   save()
}
const settingPosts=()=>{
   drawerVisible.value = true;
}
const deletePost=()=>{
   drawerVisible.value=false;
   deletePosts(editInfo.value.id)
   .then(ret=>{
      MessagePlugin.success('己删除')
   })
   .catch(e=>{
     if(e.message)
     {
       MessagePlugin.error(e.message)
     }else
     {
       MessagePlugin.error(e.msg)
     }
   })
}


const tagOptions=ref([])
const getTags= ()=>{
  //nextTick(()=>{
    getTagsList({current:1,pageSize:30})
         .then(ret=>{
            tagOptions.value=ret.items.map(tag=>({label:tag.name,value:tag.id}))
          // console.log(JSON.stringify(tagOptions.value))
         })
  //})

  }

//meta
const metaData=ref({
  post_id:'',
  meta_title:'',
  meta_description:''
})
const saveMetaData=()=>{
  if(metaData.post_id!='')
   saveMeta(metaData.value)
   .then(ret=>{
     //MessagePlugin.success('保存成功')
   })
}



getPostsInfo()

onMounted(()=>{
  getTags();
})

watch(()=>route.params.id,
()=>{
  //console.log('route.params.id',route.params.id)
  //console.log('postsId.value',postsId.value)
  if(route.params.id!=postsId.value)
  {
    getPostsInfo()
  }

})

</script>

<style scoped>
.t-card__header{
  padding-bottom: 0px;
}
.t-card__body{
  padding-top:0px;
}
</style>
